package thread;

/**
 * @Author: Administrator
 * @Date: 2023/2/8 21:10
 */

public class VolatileDemo {


    public static void main(String[] args) throws InterruptedException {
        //1问题
//        problem();
        //2.解决
//        solv1();
        solv2();
//        solv3();


    }

    //体现了变量flag 在不同线程间不可见性
    static boolean flag=false;
    public static void problem() throws InterruptedException {

        new Thread(()->{
            int i=0;

            while (!flag){
                i++;
            }
        }).start();
        Thread.sleep(3000);
        flag=true;
        System.out.println("结束");
    }

    //解决1
    static volatile boolean flag2=false;
    public static void solv1() throws InterruptedException {

        new Thread(()->{
            int i=0;

            while (!flag2){
                i++;
            }
        }).start();
        Thread.sleep(3000);
        flag2=true;
        System.out.println("结束");
    }
    //解决1
    static  boolean flag3=false;
    public static void solv2() throws InterruptedException {
        new Thread(()->{
            int i=0;
            while (!flag3){
                i++;
                try {
                    Thread.sleep(0);//会涉及同步
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
        Thread.sleep(3000);
        flag3=true;
        System.out.println("结束");
    }
    //解决1
    static volatile boolean flag4=false;
    public static void solv3() throws InterruptedException {

        new Thread(()->{
            int i=0;

            while (!flag4){
                i++;
                System.out.println("-");//io涉及同步
            }
        }).start();
        Thread.sleep(3000);
        flag4=true;
        System.out.println("结束");
    }


}

